package short_semester.questionnaire_planet.controller;

import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import short_semester.questionnaire_planet.dao.QuestionSequenceRecordDao;
import short_semester.questionnaire_planet.dao.QuestionnaireDao;
import short_semester.questionnaire_planet.dao.QuestionnaireRecordDao;
import short_semester.questionnaire_planet.dao.UserDao;
import short_semester.questionnaire_planet.entity.User;
import short_semester.questionnaire_planet.pojo.Questionnaire;
import short_semester.questionnaire_planet.pojo.QuestionnaireRecord;
import short_semester.questionnaire_planet.response.CommonResponse;
import short_semester.questionnaire_planet.response.ManageQuestionnaireController.CheckQaResponse;
import short_semester.questionnaire_planet.service.QRCodeService;
import short_semester.questionnaire_planet.service.editService.QuestionnaireService;
import short_semester.questionnaire_planet.service.editService.RelationService;

import java.util.*;


@RestController
@RequestMapping("/api")
public class ManageQuestionnaireController {

    @Autowired
    private QuestionnaireDao questionnaireDao;

    @Autowired
    private UserDao userDao;
    
    @Autowired
    QRCodeService qrCodeService;
    
    @Autowired
    QuestionnaireService questionnaireService;

    @Autowired
    QuestionnaireRecordDao questionnaireRecordDao;

    @Autowired
    QuestionSequenceRecordDao questionSequenceRecordDao;
    
    @Autowired
    RelationService relationService;
    
    //搜索功能
    @PostMapping("/qamanage/info")
    public CommonResponse getQuestionnaireInfo(
            @RequestParam("id") Integer id,
            @RequestParam(value = "key",required = false) String key
    ) {
        CommonResponse cr = new CommonResponse();
        try {
            Optional<User> optionalUser = userDao.findById(id);
            List<Questionnaire> resultList = new ArrayList<>();
            List<Questionnaire> questionnaireList = questionnaireDao.
                    findByUser(optionalUser.get());
            if (questionnaireList.size() == 0) {
                cr.setCode(1);
                cr.setMsg("该用户没有创建过问卷");
            } else if(key == null||key.trim().equals("")){
                for (Questionnaire item : questionnaireList) {
                    if (!item.getIsDeleted())
                        resultList.add(item);
                }
                cr.setCode(0);
                cr.setMsg("Success");
                cr.setData(resultList);
            } else {
                String[] keys = key.trim().split(" ");
                for (String s : keys) {
                    List<Questionnaire> list = questionnaireDao.findByUserAndTitleNotNullAndTitleContainingAndIsDeletedFalse(optionalUser.get(), s);
                    for (Questionnaire questionnaire : list) {
                        if(!resultList.contains(questionnaire))
                            resultList.add(questionnaire);
                    }

                }
                cr.setCode(0);
                cr.setMsg("Success");
                cr.setData(resultList);
            }
        } catch (Exception e){
            cr.error(e.getMessage());
            e.printStackTrace();
        }
        return cr;
    }


    /**
     * 验证某问卷是否由某人所创
     * @param userId
     * @param quesId
     * @return CommonResponse
     */
    @PostMapping("/qamanage/checkqa")
    public CommonResponse checkQa(
            @RequestParam("userid") Integer userId,
            @RequestParam("qaid") Integer quesId
    ) {
        CommonResponse cr = new CommonResponse();
        Optional<Questionnaire> ques = questionnaireDao.findById(quesId);
        if (!ques.isPresent()) {
            cr.setCode(1);
            cr.setMsg("没有该id对应的问卷");
        }
        else {
            User userOfQues = ques.get().getUser();
            CheckQaResponse response = new CheckQaResponse();
            response.setIsCreated(userOfQues.getId().equals(userId));
            cr.setCode(0);
            cr.setMsg("Success");
            cr.setData(response);
        }
        return cr;
    }

    /**
     * 删除问卷
     * @param id
     * @return
     */
    @PostMapping("/qamanage/deleteqa")
    public CommonResponse deleteQues(
            @RequestParam("qaid") Integer id
    ) {
        CommonResponse cr = new CommonResponse();
        Optional<Questionnaire> ques = questionnaireDao.findById(id);
        if (!ques.isPresent()) {
            cr.setCode(1);
            cr.setMsg("没有该问卷");
        }
        else {
            cr.setCode(0);
            cr.setMsg("Success");
            ques.get().setIsPosted(false);
            ques.get().setIsDeleted(true);
            ques.get().setDeleteDate(new Date());
            questionnaireDao.save(ques.get());
        }
        return cr;
    }

    /**
     * 从回收站恢复问卷
<<<<<<< HEAD
     * @param 
=======
     * @param list
>>>>>>> refs/remotes/origin/dev
     * @return
     */
    @PostMapping("/qamanage/recoverqa")
    public CommonResponse recoverQues(
<<<<<<< HEAD
            @RequestParam("qaid") List<Integer> ids
    ) {
        CommonResponse cr = new CommonResponse();
//        Optional<Questionnaire> ques = questionnaireDao.findById(ids);
//        if (!ques.isPresent()) {
//            cr.setCode(1);
//            cr.setMsg("没有该问卷");
//        }
//        else {
//            cr.setCode(0);
//            cr.setMsg("Success");
//            ques.get().setIsDeleted(false);
//            ques.get().setDeleteDate(null);
//            questionnaireDao.save(ques.get());
//        }
        
        try {
            for (Questionnaire questionnaire : questionnaireDao.findAllById(ids)) {
                questionnaire.setIsDeleted(false);
                questionnaireDao.save(questionnaire);
            }
        }catch (Exception e){
            
=======
            @RequestParam("ids[]") List<Integer> list
            ) {
        CommonResponse cr = new CommonResponse();
        for (Integer id: list) {
            Optional<Questionnaire> ques = questionnaireDao.findById(id);
            if (!ques.isPresent()) {
                cr.setCode(1);
                cr.setMsg("没有该问卷");
            }
            else {
                cr.setCode(0);
                cr.setMsg("Success");
                ques.get().setIsDeleted(false);
                ques.get().setDeleteDate(null);
                questionnaireDao.save(ques.get());
            }
>>>>>>> refs/remotes/origin/dev
        }
        
        return cr;
    }

    /**
     * 从数据库删除问卷,所有记录都删除
<<<<<<< HEAD
     * @param 
=======
     * @param list
>>>>>>> refs/remotes/origin/dev
     * @return
     */
    @PostMapping("/qamanage/deleteqatot")
    public CommonResponse deleteQuesTotally(
<<<<<<< HEAD
            @RequestParam("qaid") List<Integer> ids){
        CommonResponse cr = new CommonResponse();
        
//        Optional<Questionnaire> ques = questionnaireDao.findById(id);
        for (Questionnaire questionnaire : questionnaireDao.findAllById(ids)) {
            cr=questionnaireService.deleteQuestion(questionnaire);
            questionnaireDao.delete(questionnaire);
=======
            @RequestParam("ids[]") List<Integer> list){
        CommonResponse cr = new CommonResponse();
        for (Integer id: list) {
            Optional<Questionnaire> ques = questionnaireDao.findById(id);
            if (!ques.isPresent()) {
                cr.setCode(1);
                cr.setMsg("没有该问卷");
            }
            else {
                cr=questionnaireService.deleteQuestion(ques.get());
                questionnaireDao.delete(ques.get());
            }
>>>>>>> refs/remotes/origin/dev
        }
        
        
        
        return cr;
    }

    /**
     * 获取删除的问卷信息（没有彻底删除的问卷）
     * @param id
     * @return
     */
    @PostMapping("/qamanage/deletedqa")
    public CommonResponse getDeleteQa(
            @RequestParam("id") Integer id){
        CommonResponse cr = new CommonResponse();
        try{
            Optional<User> optionalUser  = userDao.findById(id);
            if(!optionalUser.isPresent()){
                cr.setCode(1);
                cr.setMsg("没有查找到此人");
            }
            else{
                User user = optionalUser.get();
                List<Questionnaire> questionnaires = questionnaireDao.findByUser(user);
                List<Questionnaire> resultList = new ArrayList<Questionnaire>();
                for (Questionnaire questionnaire : questionnaires) {
                    if(questionnaire.getIsDeleted()){
                        resultList.add(questionnaire);
                    }
                }
                cr.setCode(0);
                cr.setMsg("查找成功");
                cr.setData(resultList);

            }

        }catch (Exception e){
            cr.error(e.getMessage());
        }

        return cr;
    }

    /**
     * 停止问卷发布
     * @param id
     * @return
     */
    @PostMapping("/qamanage/update/stopPublish")
    public CommonResponse stopPublish(
            @RequestParam("id") Integer id){
        CommonResponse cr = new CommonResponse();
        try{
            Optional<Questionnaire> optional = questionnaireDao.findById(id);
            if(!optional.isPresent()){
                cr.setCode(1);
                cr.setMsg("查无此问卷");
            }
            else{
                Questionnaire questionnaire = optional.get();
                questionnaire.setIsPosted(false);
                questionnaire.setCloseDate(new Date());

                questionnaireDao.save(questionnaire);
                cr.setCode(0);
                cr.setMsg("成功将此问卷状态更改为未发布");
            }


        }catch(Exception e){
            cr.error(e.getMessage());
        }


        return cr;
    }
    
    @PostMapping("qamanage/createQA")
    public CommonResponse createQA(
            @RequestParam Integer id,
            @RequestParam String type){
        CommonResponse response = new CommonResponse();
        
        try {
            User user = userDao.getById(id);
            if(user==null){
                response.error("用户不存在");
                return response;
            }

            Questionnaire questionnaire = new Questionnaire();
            questionnaire.setUser(user);
            if(type!=null&&!type.trim().equals(""))
                questionnaire.setType(type);
            questionnaire = questionnaireDao.save(questionnaire);
            response=questionnaireService.addQuestionnaire(type,questionnaire);

        }catch (Exception e){
            e.printStackTrace();
            response.error(e.getMessage());
        }
        return response;

    }
    
    @PostMapping("/qamanage/update/publish")
    public CommonResponse publish(@RequestParam Integer id,@RequestParam String type){
        CommonResponse response = new CommonResponse();
        
        try {
            
            Questionnaire questionnaire = questionnaireDao.getById(id);
            questionnaire.setIsPosted(true);
            if(questionnaire.getPostDate()==null){
                questionnaire.setPostDate(new Date());
            }
            questionnaire.setLatestPostDate(new Date());
            
            //创建图片
            String uuid = UUID.randomUUID().toString();
            String img = qrCodeService.createQRCode2File(uuid,type);
            questionnaire.setImg(uuid);
            //TODO:验证关联顺序
            relationService.relationVertify(questionnaire);
            questionnaireDao.save(questionnaire);
            
            Map<String, String> map = new HashMap<>();
            map.put("url",qrCodeService.toQurl(uuid,type));
            map.put("img",img);
            response.setData(map);
        }catch (Exception e){
            e.printStackTrace();
            response.error(e.getMessage());
        }
        
        return response;
    }

    @PostMapping("qamanage/copy")
    public CommonResponse copyQuestionnaire(@RequestParam Integer id,@RequestParam("qid") Integer questionnaireId){
        CommonResponse response = new CommonResponse();
        
        try {
            questionnaireService.copy(id,questionnaireId);
        }catch (Exception e){
            e.printStackTrace();
            response.error("复制错误"+e.getMessage());
        }
        
        return response;
    }
    
    @PostMapping("qamanage/link")
    public CommonResponse getLink(@RequestParam("qid") Integer questionnaireId){
        CommonResponse response = new CommonResponse();
        
        try {
            Questionnaire questionnaire = questionnaireDao.getById(questionnaireId);
            Map<String, String> map = new HashMap<>();
            map.put("url",qrCodeService.toQurl(questionnaire.getImg(),questionnaire.getType()));
            map.put("img",qrCodeService.toImgurl(questionnaire.getImg()));
            response.setData(map);
        }catch (Exception e){
            e.printStackTrace();
            response.error(e.getMessage());
        }
        
        return response;
    }
    
    @PostMapping("qamanage/changeLink")

    public CommonResponse changeLink(@RequestParam("qid") Integer questionnaireId){
        CommonResponse response = new CommonResponse();

        try {
            Questionnaire questionnaire = questionnaireDao.getById(questionnaireId);
            qrCodeService.removeImg(questionnaire.getImg());
            questionnaire.setImg(null);
            questionnaire.setImg(UUID.randomUUID().toString());
            questionnaireDao.save(questionnaire);
            Map<String, String> map = new HashMap<>();
            map.put("url",qrCodeService.toQurl(questionnaire.getImg(),questionnaire.getType()));
            map.put("img",qrCodeService.toImgurl(questionnaire.getImg()));
            response.setData(map);
        }catch (Exception e){
            e.printStackTrace();
            response.error(e.getMessage());
        }

        return response;
    }

    //删除问卷的全部答卷信息
    @PostMapping("qamanage/delAns")
    public CommonResponse deleteAnswer(
            @RequestParam("questionnaireId") Integer questionnaireId){
        CommonResponse cr = new CommonResponse();
        Optional<Questionnaire> ques = questionnaireDao.findById(questionnaireId);
        if (!ques.isPresent()) {
            cr.setCode(1);
            cr.setMsg("没有该问卷");
        }
        else {
            Questionnaire questionnaire = ques.get();
            cr=questionnaireService.deleteAnswer(questionnaire);
            questionnaireRecordDao.deleteByQuestionnaire(questionnaire);
            questionnaire.setCount(0);
            questionnaireDao.save(questionnaire);
        }
        return cr;

    }

}
